package com.mca.framework.completableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zhoupeng
 * @createTime: 2025年07月07日 20:48:26
 * @version: 1.0
 * @Description:
 * @copyright:
 */
public class AcceptEitherDemo {

    public static void main(String[] args) {
        //创建可固定长度线程池
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        CompletableFuture future1 =  CompletableFuture.supplyAsync(() ->{
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("future1:"+Thread.currentThread().getName());
            return "hello";
        },executorService);

        CompletableFuture future2 = CompletableFuture.supplyAsync(()->{
            try {
                TimeUnit.SECONDS.sleep(6);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("future2:"+Thread.currentThread().getName());
            return "itheima";
        },executorService);
       //当 future1 或者 future2 其中任意一个率先完成时，就会执行传入的函数
        //acceptEitherAsync 属于 CompletableFuture 类的方法，其作用是在两个 CompletableFuture 对象（也就是 future1 和 future2）中，只要有一个完成，就会执行指定的操作。
        CompletableFuture completableFuture = future1.acceptEitherAsync(future2, (value) -> {
            System.out.println(value);
            executorService.shutdown();
        }, executorService);
//        Object v = completableFuture.get();
//        System.out.println(v);
    }
}
